﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bamboo.Utils
{
    /// <summary>
    /// 分阶段计时器，最后输出计时清单
    /// </summary>
    public class FlowTimer
    {
        class FlowTimerItem
        {
            public string Title;
            public DateTime Time;
        }

        private List<FlowTimerItem> _list = new List<FlowTimerItem>();
        private DateTime _stopTime = DateTime.MinValue;
        /// <summary>
        /// 清空所有计时器
        /// </summary>
        public void Clear()
        {
            _list.Clear();
            _stopTime = DateTime.MinValue;
        }
        /// <summary>
        /// 开始一个新阶段计时。
        /// </summary>
        /// <param name="title"></param>
        public void Start(string title)
        {
            var t = DateTime.Now;
            StartManual(title, t);
        }

        /// <summary>
        /// 有些计时点在外部代码中，需要另外传入结束时间。
        /// </summary>
        /// <param name="title"></param>
        /// <param name="lastStepEndTime"></param>
        public void StartManual(string title, DateTime lastStepEndTime)
        {
            var item = new FlowTimerItem();
            item.Title = title;
            item.Time = lastStepEndTime;
            _list.Add(item);
        }
        /// <summary>
        /// 停止计时
        /// </summary>
        public void Stop()
        {
            _stopTime = DateTime.Now;
        }
        /// <summary>
        /// 输出计时器清单和总耗时
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            if (_list.Count == 0) return "";
            if (_stopTime == DateTime.MinValue) return "";

            StringBuilder s = new StringBuilder(4096);
            TimeSpan e;
            string etext;
            for (int i = 1; i < _list.Count; ++i)
            {
                var item1 = _list[i - 1];
                var item2 = _list[i];
                e = item2.Time - item1.Time;
                etext = e.TotalSeconds.ToString("F3");
                s.AppendLine(i + ". " + item1.Title + "，" + etext + "秒；");
            }
            //最后一项
            e = _stopTime - _list[_list.Count - 1].Time;
            etext = e.TotalSeconds.ToString("F3");
            s.AppendLine(_list.Count + ". " + _list[_list.Count - 1].Title + ", " + etext + "秒；");
            //总耗时
            e = _stopTime - _list[0].Time;
            etext = e.TotalSeconds.ToString("F3");
            s.AppendLine("<总耗时>：" + etext + "秒。");
            return s.ToString();
        }
    }
}
